package com.wanmait.teatrain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanmait.teatrain.entity.TrainingResource;
import com.wanmait.teatrain.mapper.TrainingResourceMapper;
import com.wanmait.teatrain.service.TrainingResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanmait.teatrain.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 培训资源表 服务实现类
 * </p>
 *
 * @author wanmait
 * @since 2025-10-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TrainingResourceServiceImpl extends ServiceImpl<TrainingResourceMapper, TrainingResource> implements TrainingResourceService {


    // 从配置文件读取保存路径,如要更改保存路径，请打开application.properties文件更改设置
    @Value("${file.upload.video-path}")
    private String videoPath;
    @Value("${file.upload.document-path}")
    private String documentPath;

    @Resource
    private TrainingResourceMapper trainingResourceMapper;


    //培训资源保存，需增加资源表的新增 --徐钰淞
    @Override
    public AjaxResult insert(TrainingResource trainingResource, MultipartFile file) {
        try {
            // 验证文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 获取文件原始名称和扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 生成UUID作为新文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;




            Boolean isDocument = trainingResource.getIsDocument();

            // 根据文件类型确定保存路径
            String savePath = isDocument ? videoPath : documentPath;


            // 创建保存目录（如果不存在）
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }

            // 保存文件
            File destFile = new File(savePath + File.separator + newFileName);
            file.transferTo(destFile);
            //保存数据库
            trainingResource.setResourceUrl(newFileName);
            trainingResource.setCreateTime(new Date());
            save(trainingResource);
//            trainingResourceMapper.insert(trainingResource);


//            //如果文件是文档类型，转成pdf格式
//            if (!isDocument){
//                String documentFile = com.wanmait.teatrain.utils.FileToPdfConverter.convertToPdf(new File(newFileName),savePath);
//                trainingResource.setResourceUrl(savePath + "/" + documentFile);
//                trainingResource.setCreateTime(new Date());
//                trainingResourceMapper.insert(trainingResource);
//            }
//
//
//            //如果是视频文件直接保存
//            else {
//                trainingResource.setResourceUrl(savePath + "/" + newFileName);
//                trainingResource.setCreateTime(new Date());
//                trainingResourceMapper.insert(trainingResource);
//            }





            System.out.println("文件保存成功: " + destFile.getAbsolutePath());
            System.out.println(trainingResource);

            return AjaxResult.success("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, Object> getResourceList(Integer pageNum, Integer pageSize, String resourceName) {
        // 创建分页对象
        Page<TrainingResource> page = new Page<>(pageNum, pageSize);

        // 创建查询条件
        QueryWrapper<TrainingResource> queryWrapper = new QueryWrapper<>();

        // 添加模糊搜索条件
        if (resourceName != null && !resourceName.trim().isEmpty()) {
            queryWrapper.like("resource_name", resourceName.trim());
        }

        queryWrapper.orderByAsc("id"); // 按ID正序排列

        // 执行分页查询
        Page<TrainingResource> resultPage = trainingResourceMapper.selectPage(page, queryWrapper);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", resultPage.getRecords());
        result.put("total", resultPage.getTotal());
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("totalPage", resultPage.getPages());

        return result;
    }
}
